#ifndef _SOCK_HPP
#define _SOCK_HPP

#include <iostream>
#include <cstring>
#include <error.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

class Sock
{
public:
  static const int backlog = 5;

  static int Socket()
  {
      int listen_sock = socket(AF_INET, SOCK_STREAM, 0);
      if(listen_sock == -1)
      {
          fprintf(stderr, "socket: %s\n", strerror(errno));
          exit(2);
      }

      fprintf(stdout, "Socket succed!\n");
      return listen_sock;
  }

  static void Bind(int listen_sock, uint16_t port)
  {
      struct sockaddr_in local;
      bzero(&local, sizeof(local));
      local.sin_family = AF_INET;
      local.sin_port = htons(port);
      local.sin_addr.s_addr = INADDR_ANY;
      if(bind(listen_sock, reinterpret_cast<struct sockaddr*>(&local), sizeof(local)) == -1)
      {
          fprintf(stderr, "Bind: %s\n", strerror(errno));
          exit(3);
      }

      fprintf(stdout, "Bind succed!\n");
  }

  static void Listen(int listen_sock)
  {
      if(listen(listen_sock, backlog) == -1)
      {
          fprintf(stderr, "Listen: %s\n", strerror(errno));
          exit(4);
      }

      fprintf(stdout, "Listen succed!\n");
  }

  static int Accept(int listen_sock)
  {
      struct sockaddr_in peer;
      bzero(&peer, sizeof(peer));
      socklen_t len = sizeof(peer);
      int fd = accept(listen_sock, reinterpret_cast<struct sockaddr*>(&peer), &len);
      if(fd == -1)
      {
          fprintf(stderr, "Accept: %s\n", strerror(errno));
          exit(5);
      }

      fprintf(stdout, "Accept succed!\n");
      return fd;
  }

};


#endif
